package com.zoe.vhr.handler;

import cn.hutool.core.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/07/31
 * @Description 决策管理器，当前用户的角色是否和所需要的角色匹配
 */
@Configuration
public class MyAccessDecisionManager implements AccessDecisionManager {
    private static final Logger logger = LoggerFactory.getLogger(MyAccessDecisionManager.class);

    /**
     * @param authentication 当前登录用户的信息
     * @param o
     * @param collections    当前路径所需要的角色列表
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collections) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute collection : collections) {
            if (ObjectUtil.equal(collection.getAttribute(), "ROLE_LOGIN")) {
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("非法请求！！！匿名用户");
                } else {
                    return;
                }
            }
            // 获取当前用户的角色列表
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                // 如果当前的角色和所需要的角色匹配上了,则直接return即可
                if (ObjectUtil.equal(authority.getAuthority(), collection.getAttribute())) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("非法请求！！！");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {

        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
